很有意思的一道题。

leetcode 原题:
Given a digit string, return all possible letter combinations that the number could represent.

A mapping of digit to letters (just like on the telephone buttons) is given below.

Input:Digit string “23”
Output: [“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.

给定一个数字字符串,每个数字和字母的映射参考功能机的键盘。求有多少种不同的字母组合。

这个题其实很简单。每个数字对应3-4个字母,有n个数字,输出所有可能的组合。数字顺序不能调换,是一个组合问题而不是排列问题。很直观的就想到使用回溯,递归的方法。提取第i个数字对应的字母(使用字典咯),针对每个字母递归进入第i+1个数字直到i=n,返回当前生成的字符串。

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public List<String> letterCombinations(String digits) {
ArrayList<String> list = new ArrayList<>();
if (digits.isEmpty()) {
return list;
}
String[] dict = new String[]{" ", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
letterCombinationsRecursion(digits, dict, 0, "", list);
return list;
}
private void letterCombinationsRecursion(String digits, String[] dict, int level, String out, ArrayList<String> list) {
if (level == digits.length()) {
list.add(out);
} else {
String str = dict[digits.charAt(level) - '0'];
for (int i=0; i<str.length(); i++) {
out += str.charAt(i);
letterCombinationsRecursion(digits, dict, level+1, out, list);
out = out.substring(0,out.length()-1);
}
}
}
}

思考:看到这类限定性很强,或者枚举空间很小的题,总是会松懈,这样不行,做事要严谨一点。不要什么都想着用字典啊之类的暴力的方法,多想一些漂亮的数学上的解法。
更多解法:here